package com.negative.utils;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;

public class MySSLSocketFactory extends SSLSocketFactory {
	private javax.net.ssl.SSLSocketFactory socketFactory = null;

	public static Scheme getScheme(){
		try {
			MySSLSocketFactory mySSLSocketFactory = new MySSLSocketFactory();
			return new Scheme("https", mySSLSocketFactory, 443);
		}catch (Exception e){
			System.err.println("Faild to create scheme");
			return new Scheme("https", null, 443);
		}
	}
	public MySSLSocketFactory(KeyStore truststore) throws Exception {
		super(truststore);
		socketFactory = getSSLSocketFactory();
	}

	public MySSLSocketFactory() throws Exception {
		this(null);
	}

	@Override
	public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException,
	UnknownHostException {
		return socketFactory.createSocket(socket, host, port, autoClose);
	}

	@Override
	public Socket createSocket() throws IOException {
		return socketFactory.createSocket();
	}

	javax.net.ssl.SSLSocketFactory getSSLSocketFactory() throws Exception {
		SSLContext sslContext = SSLContext.getInstance("TLS");

		TrustManager tm = new X509TrustManager() {
			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			}
			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			}
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		sslContext.init(null, new TrustManager[] { tm }, null);
		return sslContext.getSocketFactory();
	}
}
